<template>
  <Dialog title="立即认证" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="企业名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入企业名称" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="formData.contactName" placeholder="请输入联系人" />
      </el-form-item>
      <!-- <el-form-item label="手机号" prop="contactMobile">
        <el-input v-model="formData.contactMobile" placeholder="请输入手机号" />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as AuthenApi from '@/api/system/user'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()

defineOptions({ name: 'Authentication' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const isShowStatus = ref(false) // 是否显示启用状态
const formData = ref({
  id: undefined,
  name: undefined,
  contactName: undefined,
  contactMobile: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }]
  // contactMobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  resetForm()
  const { id, mobile } = wsCache.get(CACHE_KEY.USER).user
  formData.value.id = id
  formData.value.contactMobile = mobile
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['successAuth']) // 定义 success 事件，用于操作成功后的回调
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    await AuthenApi.corpAuth(formData.value)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    emit('successAuth')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    contactName: undefined,
    contactMobile: undefined
  }
  formRef.value?.resetFields()
}
</script>
